#include "Material.h"

#include <fstream>
#include <iostream>

Material::Material(const string& material) :
m_materialName(material),
m_ambient(0.0f, 0.0f, 0.0f),
m_diffuse(0.0f, 0.0f, 0.0f),
m_specular(0.0f, 0.0f, 0.0f),
m_alpha(0.0f),
m_specularCoeff(0.0f),
m_texture(""),
m_normalmap(""),
m_bumpmap(""),
m_bumpDepth(0.0f),
m_emissive(false)
{
    loadMaterial();
}

Material::~Material()
{
}

string Material::getName() const
{
    return m_materialName;
}

vec3 Material::getAmbientColor() const
{
    return m_ambient;
}

vec3 Material::getDiffuseColor() const
{
    return m_diffuse;
}

vec3 Material::getSpecularColor() const
{
    return m_specular;
}

float Material::getAlpha() const
{
    return m_alpha;
}

float Material::getSpecularCoeff() const
{
    return m_specularCoeff;
}

string Material::getTexture() const
{
    return m_texture;
}

string Material::getNormalmap() const
{
    return m_normalmap;
}

string Material::getBumpmap() const
{
    return m_bumpmap;
}

float Material::getBumpDepth() const
{
    return m_bumpDepth;
}

bool Material::isEmissive() const
{
    return m_emissive;
}

void Material::loadMaterial()
{
    string path = "Models/" + m_materialName + ".mp";
    std::ifstream mpFile(path.c_str());

    if (!mpFile.is_open())
    {
        std::cerr << "Unable to load .mp-file" << std::endl;
        return;
    }

    string mpPrefix = "";
    string trash = "";

    while (mpFile >> mpPrefix && mpFile.good())
    {        
        if (mpPrefix == "ambientColor")
        {
            mpFile >> m_ambient.x >> m_ambient.y >> m_ambient.z;
        }
        else if (mpPrefix == "diffuseColor")
        {
            mpFile >> m_diffuse.x >> m_diffuse.y >> m_diffuse.z;
        }
        else if (mpPrefix == "specularColor")
        {
            mpFile >> m_specular.x >> m_specular.y >> m_specular.z;
        }
        else if (mpPrefix == "specularCoeff")
        {
            mpFile >> m_specularCoeff;
        }
        else if (mpPrefix == "alpha")
        {
            mpFile >> m_alpha;
        }        
        else if (mpPrefix == "texture")
        {
            mpFile >> m_texture;
        }
        else if (mpPrefix == "normalmap")
        {
            mpFile >> m_normalmap;
        }
        else if (mpPrefix == "bumpmap")
        {
            mpFile >> m_bumpmap;
        }
        else if (mpPrefix == "bumpDepth")
        {
            mpFile >> m_bumpDepth;
        }
        else if (mpPrefix == "emissive")
        {
            float emissive = 0.0f;
            mpFile >> emissive;
            m_emissive = (emissive > 0.0f ? true : false);
        }
        else
        {
            std::getline(mpFile, trash);
        }
    }

    mpFile.close();
}